package com.cheetah.start.common.plugin.log;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cheetah.start.system.log.domain.SysLog;
import com.cheetah.start.system.log.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;

/**
 * 定时任务
 *
 * @author xjh
 * @create 2021/7/6
 **/
@Slf4j
@Configuration
@EnableScheduling
public class LogSchedule {
    @Autowired
    private SysLogService sysLogService;


    /**
     * 每天凌晨 1 点删除 15 天前日志
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void deleteLog() {
        QueryWrapper<SysLog> wrapper = new QueryWrapper<>();
        DateTime dateTime = DateUtil.offsetDay(new Date(), -15);
        wrapper.lt("create_time", dateTime.toJdkDate());
        int count = sysLogService.count(wrapper);
        boolean remove = sysLogService.remove(wrapper);
        if (remove) {
            log.info("凌晨1点定时任务删除:[{}]条", count);
        } else {
            log.error("凌晨1点定时任务删除失败");
        }
    }

}
